var fs = require('fs');
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

var config = require(__dirname + '/config/config.js');

var app = express();
var port = process.env.PORT || 8080;

// Connect to mongodb
var connect = function () {
    var options = {server: {socketOptions: {keepAlive: 1}}};
    mongoose.connect(config.db, options);
};
connect();

mongoose.connection.on('error', console.log);
mongoose.connection.on('disconnected', connect);

var GpsTrace = require(__dirname + '/models/GpsTrace.js');

// Static files middleware
app.use(express.static(config.root + '/public'));
app.get('/', function (req, res) {
    fs.readFile(__dirname + '/public/default.htm', 'utf-8', function (err, data) {
        if (!err) {
            res.send(data);
        }
    });
});

// bodyParser should be above methodOverride
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride(function (req, res) {
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        // look in urlencoded POST bodies and delete it
        var method = req.body._method;
        delete req.body._method;
        return method;
    }
}));

var router = express.Router();
router.route('/gpstraces')
    .get(function (req, res) {
        GpsTrace.find(function (err, gpstraces) {
            if (err) {
                return res.send(err);
            }

            res.json(gpstraces);
        });
    })
    .post(function (req, res) {
        var gps = new GpsTrace(req.body);

        gps.save(function (err) {
            if (err) {
                return res.send(err);
            }

            res.send({message: 'GPS point Added'});
        });
    });
router.route('/gpstraces/:id')
    .get(function (req, res) {
        GpsTrace.findOne({_id: req.params.id}, function (err, gpstrace) {
            if (err) {
                return res.send(err);
            }

            res.json(gpstrace);
        });
    })
    .put(function (req, res) {
        GpsTrace.findOne({_id: req.params.id}, function (err, gpstrace) {
            if (err) {
                return res.send(err);
            }

            for (prop in req.body) {
                gpstrace[prop] = req.body[prop];
            }

            // save the movie
            gpstrace.save(function (err) {
                if (err) {
                    return res.send(err);
                }

                res.json({message: 'GPS point updated!'});
            });
        });
    })
    .delete(function (req, res) {
        GpsTrace.remove({
            _id: req.params.id
        }, function (err, gpstrace) {
            if (err) {
                return res.send(err);
            }

            res.json({message: 'Successfully deleted'});
        });
    });
app.use('/api', router);

app.listen(port);
console.log('Listening on port ' + port);